package com.student.xujiang.myallstudent.retrofit2;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.student.xujiang.R;
import com.student.xujiang.myallstudent.retrofit2.retrofit2_2.Retrifit2_2Activity;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Converter;
import retrofit2.Response;
import retrofit2.Retrofit;

public class Retrofit2MainActivity extends AppCompatActivity implements Callback<String> {

    @BindView(R.id.tv_retrofit2_main_result)
    TextView tvRetrofit2MainResult;
    @BindView(R.id.activity_retrofit2_main)
    RelativeLayout activityRetrofit2Main;
    @BindView(R.id.button)
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrofit2_main);
        ButterKnife.bind(this);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://www.baidu.com")
                .addConverterFactory(
                        new Converter.Factory() {
                            @Override
                            public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
                                return new Converter<ResponseBody, String>() {
                                    @Override
                                    public String convert(ResponseBody value) throws IOException {
                                        return value.string();
                                    }
                                };
                            }
                        }
                ).build();  //转换成string  //Converter转换器
        Service service = retrofit.create(Service.class);  //通过反射得到
        Call<String> call = service.getBaidu();
        call.enqueue(this);
    }

    @Override
    public void onResponse(Call<String> call, Response<String> response) {
        tvRetrofit2MainResult.setText(response.body());
    }

    @Override
    public void onFailure(Call<String> call, Throwable t) {
        Toast.makeText(this, "请求失败" + call.request().url(), Toast.LENGTH_SHORT).show();
        t.printStackTrace();
    }

    @OnClick(R.id.button)
    public void onClick() {
        Intent intent = new Intent(Retrofit2MainActivity.this, Retrifit2_2Activity.class);
        startActivity(intent);

    }
}
